<template>
	<view
		style="width: 100%; height: 100vh; display: flex; justify-content: center; align-items: center;font-size: 26rpx;">
		<button open-type="getPhoneNumber" @getphonenumber="handleGetPhoneNumber">授权登录</button>
		<!-- <button @click="doLogin"> 授权登录</button> -->
	</view>
</template>

<script setup>
	import {
		onLoad,
		onShow
	} from "@dcloudio/uni-app"
	import {
		getPhoneNumberApi,
		getUserInfoApi,
		addCustomer
	} from "@/api/user.js"
	onShow(() => {
		doLogin()
	})
	import {
		useUserStore
	} from "@/stores/user"
	import {
		setUser
	} from "@/utils/token.js"
	const userStore = useUserStore()
	let userInfo = {}

	function doLogin() {
		uni.login({
			provider: 'weixin',
			success: function(loginRes) {
				getUserInfoApi({
					code: loginRes.code
				}).then(e => {
					Object.assign(userInfo, e.data)
					// 获取用户信息
					uni.getUserInfo({
						provider: 'weixin',
						success: function(infoRes) {
							console.log(infoRes);
							userInfo.customer_name = infoRes.userInfo.nickName
							userInfo.headimg = infoRes.userInfo.avatarUrl
							Object.assign(userInfo, infoRes.userInfo)
							console.log(userInfo, 42)
						}
					});
				})

			}
		});
	}

	const handleGetPhoneNumber = async (e) => {
		uni.showLoading({
			title: '登录中...'
		});
		getPhoneNumberApi({
			...e.detail
		}).then(e => {
			console.log(e, 21)
			userInfo.phone = e.data.phone_info.phoneNumber
			Object.assign(userInfo, e.data.phone_info)
			console.log(userInfo)
			addCustomer(userInfo).then(user => {
				console.log(user.data, 27)
				userStore.setUserInfo(user.data)
				// 本地存储也存一个 
				// setUser(JSON.stringify(user.data))
				setUser(user.data)
				uni.hideLoading();
				uni.navigateBack()
			})
		})


		// uni.showToast({
		// 	title: '用户拒绝提供手机号',
		// 	icon: 'none'
		// })

	}
</script>

<style>

</style>